<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="材料编号" prop="id">
            <el-input v-model="queryParams.id" placeholder="请输入材料编号" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="名称" prop="resName">
            <el-input v-model="queryParams.resName" placeholder="请输入名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="上传人" prop="createBy">
            <el-input v-model="queryParams.createBy" placeholder="请输入上传人" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="上传时间" prop="createTime">
            <el-date-picker clearable
              v-model="queryParams.createTime"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择上传时间"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            <el-button type="primary" @click="handleAdd" v-hasPermi="['core:resourcesSchool:add']">新增</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
       <h2>学校资源列表</h2>
      </template>

      <el-table v-loading="loading" :data="resourcesSchoolList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="材料编号" align="center" prop="id" v-if="true" />
        <el-table-column label="名称" align="center" prop="resName" />
        <el-table-column label="类型" align="center" prop="resType" >
          <template #default="scope">
            <dict-tag :options="sys_file_type" :value="scope.row.resType" />
          </template>
        </el-table-column>
        <el-table-column label="说明" align="center" prop="resDesc" />
        <el-table-column label="学校" align="center" prop="deptId">
          <template #default="scope">
            {{getSchoolById(deptOptions,scope.row.deptId)}}
          </template>
        </el-table-column>
        <el-table-column label="上传人" align="center" prop="createBy" />
        <el-table-column label="上传时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
          <template #default="scope">
              <el-button type="text" size="small"  @click="handleUpdate(scope.row)" v-hasPermi="['core:resourcesSchool:edit']">编辑</el-button>
              <el-button type="text" size="small"  @click="handleDelete(scope.row)" v-hasPermi="['core:resourcesSchool:remove']">删除</el-button>
              <el-button type="text" size="small"  @click="handleDownload(scope.row.attach)">下载</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-show="total>0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
      />
    </el-card>
    <!-- 添加或修改教学资源管理学校库对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="resourcesSchoolFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="resName">
          <el-input v-model="form.resName" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="类型" prop="resType">
          <el-select v-model="form.resType" placeholder="请选择类型" >
            <el-option
                v-for="dict in sys_file_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="说明" prop="resDesc">
          <el-input v-model="form.resDesc" placeholder="请输入说明" />
        </el-form-item>
        <el-form-item label="学校" prop="deptId">
          <el-tree-select
            
            filterable
           clearable
           v-model="form.deptId"
           :data="deptOptions"
           :props="{ value: 'deptId', label: 'deptName', children: 'children' }"
           value-key="deptId"
           placeholder="请选择学校"
           :render-after-expand="false"
         />
        </el-form-item>
        <el-form-item label="内容">
          <editor v-model="form.content" :min-height="120"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="附件内容" prop="attach" >
         <videoFileUpload  v-model="form.attach"  v-if="form.resType == '0'" />
         <imageUpload  v-model="form.attach"  v-if="form.resType == '1'" />
         <fileUpload  v-model="form.attach"  v-if="form.resType == '2'" />
       </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ResourcesSchool" lang="ts">
import { listResourcesSchool, getResourcesSchool, delResourcesSchool, addResourcesSchool, updateResourcesSchool } from '@/api/core/resourcesSchool';
import { ResourcesSchoolVO, ResourcesSchoolQuery, ResourcesSchoolForm } from '@/api/core/resourcesSchool/types';
const router = useRouter();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

import { getSubjectNameById,getTeacherNameById,getSchoolById } from '@/utils/index';
import { useSchoolList } from '@/composables/useSchoolList';
const { deptOptions, fetchSchoolList } = useSchoolList();
const { sys_user_sex } = toRefs<any>(proxy?.useDict('sys_user_sex'));
  const { sys_file_type } = toRefs<any>(proxy?.useDict('sys_file_type'));
const resourcesSchoolList = ref<ResourcesSchoolVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const resourcesSchoolFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: ResourcesSchoolForm = {
  resName: undefined,
  resType: undefined,
  resDesc: undefined,
  deptId: undefined,
  content: undefined,
  remark: undefined,
  attach: undefined
}
const data = reactive<PageData<ResourcesSchoolForm, ResourcesSchoolQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    id: undefined,
    resName: undefined,
    resType: undefined,
    createBy: undefined,
    createTime: undefined,
    params: {
    }
  },
  rules: {
    resName: [
      { required: true, message: "名称不能为空", trigger: "blur" }
    ],
    resType: [
      { required: true, message: "类型不能为空", trigger: "change" }
    ],
    resDesc: [
      { required: true, message: "说明不能为空", trigger: "blur" }
    ],
    deptId: [
      { required: true, message: "学校不能为空", trigger: "change" }
    ],
    content: [
      { required: true, message: "内容不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询教学资源管理学校库列表 */
const getList = async () => {
  loading.value = true;
  const res = await listResourcesSchool(queryParams.value);
  resourcesSchoolList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 下载按钮 */
const handleDownload = (ossId: string) => {
  proxy?.$download.oss(ossId);
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  resourcesSchoolFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: ResourcesSchoolVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  router.push('/resource/resourcesSchool/panel/');
}

/** 修改按钮操作 */
const handleUpdate = async (row?: ResourcesSchoolVO) => {
  const id = row?.id || ids.value[0]
  router.push({ path: '/resource/resourcesSchool/panel/', query: { id: id} });
}

/** 提交按钮 */
const submitForm = () => {
  resourcesSchoolFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateResourcesSchool(form.value).finally(() =>  buttonLoading.value = false);
        proxy?.$modal.msgSuccess("编辑成功");
      } else {
        await addResourcesSchool(form.value).finally(() =>  buttonLoading.value = false);
        proxy?.$modal.msgSuccess("新增成功");
      }
     
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: ResourcesSchoolVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除教学资源管理学校库编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delResourcesSchool(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('core/resourcesSchool/export', {
    ...queryParams.value
  }, `resourcesSchool_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
});
</script>
